<template>
	<view class="contianer">
		<u-navbar v-if="dataInfo.isPay=='0'" title='订单支付' leftIconColor="#1E272E"
			:titleStyle="{fontWeight:700,fontSize:'32rpx',color:'#000000'}" bgColor="#fff" :auto-back="true"></u-navbar>
		<u-navbar v-else title='查看订单' leftIconColor="#1E272E"
			:titleStyle="{fontWeight:700,fontSize:'32rpx',color:'#000000'}" bgColor="#fff" :auto-back="true"></u-navbar>
		<view class="content">
			<view class="topInfo">
				<view><text style="font-size: 34rpx;font-weight: 600;">{{comfirmData.assignName}}</text><text
						style="color: #f56c6c;">￥{{comfirmData.contractMoney}}</text></view>
				<view><text>店铺名称</text><text>{{comfirmData.storeName||""}}</text></view>
				<view><text>装修公司</text><text>{{comfirmData.companyName}}</text></view>
			</view>
			<view class="projectInfo">
				<view><text>施工负责人</text><text>{{comfirmData.projectUserName+(comfirmData.projectUserPhone||"")}}</text>
				</view>
				<view><text>详细地址</text><text style="max-width: 300rpx;flex-wrap: wrap;">{{comfirmData.address}}</text>
				</view>
				<view><text>计划完工时间</text><text>{{comfirmData.planEndTime||""}}</text></view>
				<view><text>工期（天）</text><text>{{comfirmData.duration}}</text></view>
			</view>
			<!-- <view class="projectInfo" style="height: 220rpx;" v-if="dataInfo.isPay!='0'">
				<view><text>应收</text><text>￥{{comfirmData.contractMoney}}</text></view>
				<view><text>已支付</text><text>￥{{comfirmData.payAmount||0.00}}</text></view>
				<view><text>待支付</text><text style="font-weight: 600;">￥{{comfirmData.pendingPay||0.00}}</text></view>
			</view> -->
			<view class="projectInfo" style="height: 100rpx;">
				<!-- <view style="padding-bottom: 12rpx;" @click="checkPayList"><text>查看付款记录</text><text><u-icon
							name="arrow-right"></u-icon></text></view> -->
				<!-- <view>
					<u-line length="100%"></u-line>
				</view> -->
				<view style="padding-top: 12rpx;" @click="lookSign(dataInfo.signedContractAddress||dataInfo.contractAddressPdf)">
					<text>查看合同</text><text style="margin-top: 5rpx;"><u-icon name="arrow-right"></u-icon></text>
				</view>
			</view>
			<view v-if="comfirmData.payCertificateArr && comfirmData.payCertificateArr.length" class="projectInfo" style="height: auto;background-color: #fff;">
				<text>付款凭证</text><text style="margin-top: 5rpx;"><u-icon name="arrow-right"></u-icon></text>
				<view class="imgWrapper flex" style="flex-wrap: wrap;justify-content: flex-start;">
					<image v-for="(url,index) in comfirmData.payCertificateArr" @click="viewImgChoose(i,index)" :src="'https://'+url" mode="" style="width: 203rpx;height: 166rpx;margin: 10rpx;"></image>
				</view>
			</view>
			<view v-if="paymentHistoryList.length" class="projectInfo" style="height: auto;background-color: #fff;">
				<text>付款记录</text><text style="margin-top: 5rpx;"><u-icon name="arrow-right"></u-icon></text>
				<view class="pay-history-table">
					<view class="table-head flex-row bload">
						<view class="table-td-l flex-center ">
							时间
						</view>
						<view class="table-td-c flex-center">
							类型
						</view>
						<view class="table-td-r flex-center">
							金额
						</view>
					</view>
					<scroll-view scroll-y class="history-table-scroll">
					  
					   <view class="table-body flex-row" v-for="(item,index) in paymentHistoryList">
							<view class="table-td-l flex-center">
							{{item.payTime}}
							</view>
							<view class="table-td-c flex-center">
								{{fifterType(item.supplierType)}}
							</view>
							<view class="table-td-r flex-center">
								{{item.payAmount}}元
							</view>
					   </view>
					</scroll-view>
				</view>
				
			</view>
			
			
			<!-- 付款 -->
		</view>
		<!-- <view class="" style="width: 100%;height:160rpx;">
			
		</view> -->
		<!-- v-if="dataInfo.status==2||dataInfo.status==1||dataInfo.status==0||dataInfo.status==3" -->
		<view class="payButtom" v-if="dataInfo.isPay=='0'&&loginType==4">
			<view style="display: flex;align-items: center;">
				<text style="font-weight: 600;">实付：</text>
				<view style="width: 200rpx; height: 70rpx;border: 1px solid #eee;">
					<u-input v-model="payAmount" :disabled="false"></u-input>
				</view>
			</view>
			<view style="display: flex;">
				 <!-- v-if="comfirmData.payAmount<=0" -->
				<view
					style="width:160rpx; height: 75rpx;background-color: #13989A;line-height: 75rpx;text-align: center;border-top-left-radius: 20rpx;border-bottom-left-radius: 20rpx;color: #fff;font-weight: 600;font-size: 26rpx;"
					@click="downPay">线下支付</view>
				 <view v-if="comfirmData.payAmount>0"
					style="width:160rpx; height: 75rpx;background-color: #f56c6c;line-height: 75rpx;text-align: center;border-top-right-radius: 20rpx;border-bottom-right-radius: 20rpx;color: #fff;font-weight: 600;font-size: 26rpx;"
					@click="payNow">立即支付</view>
				<view v-if="comfirmData.payAmount<=0"
					style="width:160rpx; height: 75rpx;background-color: #f56c6c;line-height: 75rpx;text-align: center;border-radius:0 20rpx 20rpx 0;color: #fff;font-weight: 600;font-size: 26rpx;"
					@click="payNow">立即支付</view>
			</view>
		</view>
		
		<u-modal :show="officalPayDialog" :title="title" @confirm="offlinePayment" confirmColor="#f56c6c"
			@cancel="cancel" :showCancelButton='true'>
			<view class="slot-content">
				<upload v-if="officalPayDialog" name="overImage" @uploadFile="uploadOverImge"></upload>
			</view>
		</u-modal>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loginType: uni.getStorageSync('loginType'),
				dataInfo: {},
				comfirmData: {},
				overImage:[],
				officalPayDialog: false,
				title: "付款凭证",
				content: '确认此订单为线下支付吗？',
				payAmount: "",
				payAmountOld:0,
				getUserId: "",
				paymentHistoryList:[]
			}
		},
		onLoad(option) {
			this.dataInfo = option
			console.log(option);
		},
		onShow() {
			this.getPageData()


			// #ifdef MP-WEIXIN
			this.uniLogin()
			//#endif
		},
		methods: {
			downPay(){
				if(this.payAmount < this.comfirmData.pendingPay){
					return this.$u.toast('线下支付仅支持全款!')
				}
				this.officalPayDialog=true
			},
			fifterType(supplierType){
			  if(!supplierType){
				  return ''
			  }else if(supplierType === 1){
				  return '装修'
			  }else if(supplierType === 2){
				  return '冷链'
			  }else if(supplierType === 3){
				  return '货架'
			  }else if(supplierType === 4){
				  return '监控'
			  }else if(supplierType === 5){
				  return '门窗'
			  }else if(supplierType === 6){
				  return '广告'
			  }
			},
			viewImgChoose(i,index){
				uni.previewImage({
					current:index,
					urls:this.comfirmData.payCertificateArr.map(url=>'http://'+url),
					longPressActions: {
						itemList: ['保存图片'],
						success: data=> {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
							uni.closePreviewImage()
							/* 保存图片到系统相册 */
							if(data.tapIndex==0){
								uni.getImageInfo({
											src:this.comfirmData.payCertificateArr.map(url=>'http://'+url)[data.index],
											success: function(res) {
												console.log(res)
												uni.saveImageToPhotosAlbum({ //保存图片到系统相册。
													filePath:res.path, //图片文件路径
													success: function() {
														uni.showToast({
															title: '图片保存成功',
															icon: 'none',
														});
													},
													fail: function(e) {
														console.log(e);
														uni.showToast({
															title: '图片保存失败',
															icon: 'none',
														});
													},
												});
											},
											fail: function(e) {
												console.log(e);
												uni.closePreviewImage()
												uni.showToast({
													title: '图片保存失败',
													icon: 'none',
												});
											},
										})
							}
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				})
			},
			getPageData() {
				uni.$u.http.get('/contract/getConfirmOrderInfo', {
					params: {
						contractId: this.dataInfo.contractId
					}
				}).then(res => {
					this.comfirmData = res
					this.payAmount = res.pendingPay
					this.payAmountOld = res.pendingPay
					if(!res.assignTaskId){
						return
					}
					uni.$u.http.post('/contract/getMyPaymentHistoryVo',{assignTaskId:res.assignTaskId}).then(ress => {
						console.log(res, "付款记录列表");
						if(ress && ress.list){
							this.paymentHistoryList = []
							this.paymentHistoryList = ress.list
						}
					})
				})
				
			},
			// async Wxlogin() {
			// 	var res = await wx.login()
			// 	console.log(res.code,"uni.login")
			// 	if (res.code) {
			// 		this.getUserId = res.code
			// 	}
			// },
			async uniLogin() {
				try {
					const loginRes = await new Promise((resolve, reject) => {
						uni.login({
							provider: 'weixin',
							success: (res) => resolve(res),
							fail: (err) => reject(err)
						});
					});
					this.getUserId = loginRes.code;
					return loginRes;
				} catch (error) {
					console.error('login fail:', error);
					throw error;
				}
			},
			uploadOverImge(msg){
				this.overImge=msg.files
			},
			checkPayList() {
				uni.navigateTo({
					url: `/pages/comfirmPay/payList?contractId=${this.dataInfo.contractId}`
				})
			},
			offlinePayment() {
				if(!this.overImge.length){
					return this.$u.toast('请上传付款凭证!')
				}
				const data = {
					assignTaskId: this.comfirmData.assignTaskId,
					payCertificateArr:this.overImge,
					supplierTaskId:this.dataInfo.supplierId
				}
				uni.$u.http.post("/contract/updateContractPayStatus", data).then(res => {
					if (res == 1) {
						this.officalPayDialog = false
						uni.showToast({
							title: '操作线下支付',
							duration: 1000
						});
						uni.navigateBack({
							delta: 1
						})
					}
				})
			},
			cancel() {
				this.officalPayDialog = false
				this.overImage=[]
				uni.showToast({
					title: '取消线下支付',
					duration: 1000
				});
			},

			payNow() {
				if (!this.payAmount) return uni.showToast({
					title: '输入金额！',
					icon: 'error',
					duration: 1500
				});
				if (!uni.$u.test.amount(this.payAmount)) return uni.showToast({
					title: '输入正确金额！',
					icon: 'error',
					duration: 1500
				});
				if (this.payAmount < 1) return uni.showToast({
					title: '付款金额不得低于1元！',
					icon: 'error',
					duration: 1500
				});
				if (this.payAmount > this.payAmountOld) return uni.showToast({
					title: '付款金额超出该笔订单原始金额！',
					icon: 'none',
					duration: 1500
				});
				//#ifdef APP-PLUS
				uni.navigateTo({
					url: `/pages/paying/index?contractId=${this.dataInfo.constractId}&payAmount=${this.payAmount}`
				})
				// #endif
				// let that = this
				// uni.login({
				// 	provider: 'weixin',
				// 	success: function(loginRes) {
				// 		console.log('login success:', loginRes.code);
				// 		that.getUserId = loginRes.code
				// 	},
				// 	fail: function(err) {
				// 		console.error('login fail:', err);
				// 	}
				// });
				// #ifdef MP-WEIXIN
				let data = {};

				uni.$u.http.get("/contract/getOpenId").then(res => {
					if (res) {
						this.getUserId = res;
						data = {
							contractId:this.comfirmData.contractId,
							supplierType:JSON.parse(this.dataInfo.supplierType),
							openId: this.getUserId,
							// contractId: this.dataInfo.constractId,
							payAmount: this.payAmount,
							payType: 1,
						};
					} else {
						data = {
							code: this.getUserId,
							supplierType:JSON.parse(this.dataInfo.supplierType),
							// contractId: this.dataInfo.constractId,
							contractId:this.comfirmData.contractId,
							payAmount: this.payAmount,
							payType: 1,
						};
					}
					return uni.$u.http.post("/contract/pay/alipay", data)
				}).then(res => {
					// console.log('第一个失败',res);
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: res.timestamp,
						nonceStr: res.nonce_str,
						package: res.package,
						signType: res.sign_type,
						paySign: res.pay_sign,
						success: function(res) {
							uni.navigateTo({
								url: '/pages/comfirmPay/paySuccess'
							});
						},
						fail: function(err) {
							console.log('失败',err);
							// uni.showToast({
							// 	title: '支付失败！',
							// 	icon: 'error',
							// 	duration: 1000
							// });
						}
					});
				}).catch(err => {
					console.error('请求失败:', err);
				});


				// #endif
			},
			lookSign(url) {
				if (url != 'null' && url) {
					uni.showLoading({
						title: '合同下载中...'
					})
					uni.downloadFile({
						url: `https://${url}`,
						success: function(res) {
							var filePath = res.tempFilePath;
							uni.hideLoading();
							uni.openDocument({
								filePath: filePath,
								showMenu: true,
								success: function(res) {
									console.log('打开文档成功');
								}
							});
						},
						fail: () => {
							uni.hideLoading();
							uni.$u.toast('合同下载失败,请联系管理员 :)');
						}
					});
				} else {
					uni.$u.toast('合同未上传，不可查看!');
				}

			},
		}
	}
</script>
<style lang="less" scoped>
	// #app {
	// 	background-color: azure;
	// }
	
	.pay-history-table{
		width: 100%;
		// height: 400rpx;
		// background-color: red;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		.bload{
			font-weight: bold;
		}
		.flex-center{
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.flex-row{
			display: flex;
			align-items: center;
			flex-direction: row;
		}
		.table-head{
			width: 100%;
			view{
				height: 60rpx;
			}
			.table-td-l{
				width: 40%;
				border: 1rpx solid gray;
			}
			.table-td-c{
				width: 30%;
				border: 1rpx solid gray;
				border-left: none;
			}
			.table-td-r{
				width: 30%;
				border: 1rpx solid gray;
				border-left: none;
			}
		}
		.history-table-scroll{
			width: 100%;
			min-height: 100rpx;
			max-height: 300rpx;
			
			
			.table-body{
				width: 100%;
				view{
					height: 60rpx;
					font-size: 22rpx;
				}
				.table-td-l{
					width: 40%;
					border: 1rpx solid gray;
					border-top: none;
					
				}
				.table-td-c{
					width: 30%;
					border: 1rpx solid gray;
					border-left: none;
					border-top: none;
				}
				.table-td-r{
					width: 30%;
					border: 1rpx solid gray;
					border-left: none;
					border-top: none;
				}
			}
		}
	}
	
	
	.content {
		width: 700rpx;
		position: absolute;
		top: 195rpx;
		left: 50%;
		transform: translate(-50%, 0);
	}

	.topInfo {
		width: 700rpx;
		height: 220rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		padding: 25rpx;
		box-sizing: border-box;
		border: 5rpx solid #fff;
		background: linear-gradient(90deg, #B7DFDF, #ffffff 80%);
		border-radius: 20rpx;

		view {
			display: flex;
			justify-content: space-between;

			text {
				font-size: 30rpx;
				display: block;
			}
		}
	}

	.projectInfo {
		width: 700rpx;
		height: 300rpx;
		background-color: #fff;
		margin-top: 20rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		padding: 25rpx;
		box-sizing: border-box;
		border-radius: 20rpx;

		view {
			display: flex;
			justify-content: space-between;

			text {
				font-size: 30rpx;
				display: block;
			}
		}
	}

	.payButtom {
		width: 750rpx;
		height: 160rpx;
		background-color: #fff;
		position: fixed;
		bottom: 0;
		display: flex;
		align-items: flex-start;
		padding: 25rpx;
		justify-content: space-between;
		box-sizing: border-box;
		
		
	}
</style>